use std::{cell::RefCell, collections::HashMap, rc::Rc, str};

use http_muncher::{Parser, ParserHandler};

pub struct HttpHandler {
    current_key: Option<String>,
    headers: Rc<RefCell<HashMap<String, String>>>,
}
impl HttpHandler {
    pub fn new(headers: Rc<RefCell<HashMap<String, String>>>) -> Self {
        Self {
            current_key: None,
            headers,
        }
    }
}

impl ParserHandler for HttpHandler {
    fn on_header_field(&mut self, _: &mut Parser, data: &[u8]) -> bool {
        let key = str::from_utf8(data).unwrap().to_string();
        self.current_key = Some(key);
        true
    }
    fn on_header_value(&mut self, _: &mut Parser, data: &[u8]) -> bool {
        self.headers.borrow_mut().insert(
            self.current_key.clone().unwrap(),
            str::from_utf8(data).unwrap().to_string(),
        );
        true
    }
}
